package com.example.springbootzuoye.controller;

import com.example.springbootzuoye.entity.Emp;
import com.example.springbootzuoye.entity.Page;
import com.example.springbootzuoye.entity.VueData;
import com.example.springbootzuoye.service.EmpService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * (Emp)表控制层
 *
 * @author makejava
 * @since 2022-12-23 00:38:34
 */
@CrossOrigin
@Controller
@RequestMapping("emp")
public class EmpController {
    /**
     * 服务对象
     */
    @Autowired
    private EmpService empService;

    //配合Jsp文件使用，查询
    @GetMapping("getAll")
    public String getAll(HttpServletRequest request){
        List<Emp> listEmp = empService.getAll();
        request.setAttribute("listEmp",listEmp);
        return "emp";
    }

    //配合Jsp文件使用，添加
    @PostMapping("add")
    @ResponseBody
    public Boolean add(Emp emp){
        System.out.println("emp = " + emp);
        Boolean i = empService.add(emp);
        return i;
    }

    /*
        配合Vue文件使用，查询
        要求显示第二页数据，每页显示5条数据
     */
    @GetMapping("queryAll")
    @ResponseBody
    public VueData queryAll(){
        //查询出来所有数据
        List<Emp> listEmp = empService.getAll();
        //筛选数据(利用Page实体类)
        Stream<Emp> empStream = listEmp.stream().skip((2 - 1) * new Page().getLimit()).limit(new Page().getLimit());
        //将Stream再转换为List集合
        List<Emp> listEmp1 = empStream.collect(Collectors.toList());
        //System.out.println("listEmp1 = " + listEmp1);
        return new VueData(listEmp1);
    }

    //配合Vue文件使用，添加
    @PostMapping("addEmp")
    @ResponseBody
    public VueData addEmp(Emp emp){
        System.out.println("emp = " + emp);
        Boolean i = empService.add(emp);
        return new VueData(i);
    }
}
